package com.omi.iberolactalpreventa;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import com.omi.iberolactalpreventa.objects.AdapterVisita;
import com.omi.iberolactalpreventa.objects.ItmVisita;
import android.content.DialogInterface.OnClickListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Visitas extends Activity{
	
 	private EditText txtCodCliente;
	private CheckBox chkAusente;
	private EditText txtComments;
	private Button btnAniadir;
	private ListView lstComments;
	private String idClient;
	private ItmVisita itmSelected;
	private MenuItem itmBorrar;
	private MenuItem itmModif;
	private Builder dlgDelete;
	private Toast toast;
	private ListView lstFechaVisitas;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_visitas);
		
		Bundle extras = getIntent().getExtras();
		if(extras!=null)
		{
			idClient = extras.getString("idClient");
		}
		
		txtCodCliente = (EditText)findViewById(R.id.txtCodCliente);
		chkAusente = (CheckBox)findViewById(R.id.chkAusente);
		txtComments = (EditText)findViewById(R.id.txtComments);
		btnAniadir = (Button)findViewById(R.id.btnAniadir);
		lstComments = (ListView) findViewById(R.id.lstComments);
		lstFechaVisitas = (ListView)findViewById(R.id.lstFechaVisitas);
		
		lstFechaVisitas.setAdapter(Modulebase.inicializarFecha());
		
		Cursor c =Modulebase.db.ejecutarSelect(new String[]{"NOMBRE"}, "CLIENTE","COD_CLIENTE=?",new String[]{idClient});
		if(c!=null && c.moveToFirst())
		{
		//Sacamos el nombre del cliente para mostrarle:
		txtCodCliente.setText(c.getString(0));
		}
		
		cargarComments();
	
		//Definimos el funcionamiento de los dialogos:
		
		DialogInterface.OnClickListener dialogSalir = new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which==-1)
				{
					if(eliminarVisita())
					{
						toast = Toast.makeText(getApplicationContext(), "Visita eliminada correctamente", Toast.LENGTH_SHORT);
						toast.show();
					}
					cargarComments();
				}
			}
		};
				
		//Configuracion de cuadros de dialogo.
		dlgDelete = new AlertDialog.Builder(this);
		dlgDelete.setTitle("Eliminar");
		dlgDelete.setMessage("¿Esta seguro de querer eliminar el comentario seleccionado?");
		dlgDelete.setPositiveButton("Sí", dialogSalir);
		dlgDelete.setNegativeButton("No", dialogSalir);
		
		//EVENTOS:
		btnAniadir.setOnClickListener(new android.view.View.OnClickListener() {
		
			@Override
			public void onClick(View v) {
				//Si estamos añadiendo:

				if(btnAniadir.getText().equals("Modificar"))
				{
					int ausente = (chkAusente.isChecked()) ? 1 : 0;
					Modulebase.db.ejecutarNonQuery("UPDATE VISITAS SET FECHA='"+Modulebase.calendar.get(Calendar.DAY_OF_MONTH)+"/"+(Modulebase.calendar.get(Calendar.MONTH)+1)+"/"+Modulebase.calendar.get(Calendar.YEAR)+"',AUSENTE='"+ausente+"',COMENTARIO='"+txtComments.getText()+"' WHERE COD_CLIE='"+idClient+"' AND FECHA='"+itmSelected.getFecha()+"';");
					btnAniadir.setText("Añadir");
					txtComments.setText("");
					chkAusente.setChecked(false);
		    		itmModif.setTitle("Modificar");
				}
				else
				{
				//Añadimos comentario:
				
					int ausente = (chkAusente.isChecked()) ? 1 : 0;
					if(!Modulebase.db.ejecutarNonQuery("INSERT INTO VISITAS VALUES('"+idClient+"', '"+Modulebase.calendar.get(Calendar.DAY_OF_MONTH)+"/"+(Modulebase.calendar.get(Calendar.MONTH)+1)+"/"+Modulebase.calendar.get(Calendar.YEAR)+"', '"+ausente +"','"+txtComments.getText()+"');"))
					{
						toast = Toast.makeText(getApplicationContext(), "Error, ya hay un comentario con esta fecha.",Toast.LENGTH_SHORT);
						toast.show();
						return;
					}
					txtComments.setText("");
				}
				cargarComments();
				
			}
		});
		
		lstComments.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View contentView,int position, long id) {
				//Guardamos el elemento seleccionado:
				itmSelected = (ItmVisita)parent.getItemAtPosition(position);
				
				//Mostramos el menu:
				itmBorrar.setEnabled(true);
				itmModif.setEnabled(true);
				//Ocultamos el teclado:
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(txtComments.getWindowToken(), 0);
				openOptionsMenu();
				return false;
			}
		});
		
		//Evento para mostrar el datepicker:
		lstFechaVisitas.setOnItemClickListener(new OnItemClickListener() {
			 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
			@SuppressWarnings("deprecation")
			public void onItemClick(AdapterView<?> parent, View view,
		                int position, long id) {
					showDialog(100);
					}
		});
		
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}
	
	@Override
	public void onBackPressed() {
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.visitas,menu);
	    itmBorrar  = menu.findItem(R.id.itmBorrar);
		itmModif = menu.findItem(R.id.itmModif);
		itmBorrar.setEnabled(false);
		itmModif.setEnabled(false);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

	    switch (item.getItemId()) {
	    case android.R.id.home:
            finish();
            return true;
	    case R.id.itmModif:
	    	if(btnAniadir.getText().equals("Añadir"))
	    	{
	    		//Metemos el comentario en el textbox para editar:
	    		txtComments.setText(itmSelected.getComentario());
	    		//Ponemos la fecha del comentario en la lista:
	    		String[] fecha = itmSelected.getFecha().split("/");
	    		Modulebase.calendar = new GregorianCalendar(Integer.parseInt(fecha[2]), (Integer.parseInt(fecha[1])-1), Integer.parseInt(fecha[0]));
				lstFechaVisitas.setAdapter(Modulebase.inicializarFecha());
				chkAusente.setChecked(itmSelected.isAusente());
	    		btnAniadir.setText("Modificar");
	    		itmModif.setTitle("Añadir");
	    		return true;
	    	}
	    	else
	    	{
	    		btnAniadir.setText("Añadir");
				txtComments.setText("");
	    		itmModif.setTitle("Modificar");
	    	}
	    	return true;
	    case R.id.itmBorrar:
	    	dlgDelete.show();
	    	return true;
	    default:
	    	 itmBorrar.setEnabled(false);
	 		 itmModif.setEnabled(false);
	 		 return true;
	    }
	   
}
	
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		  return new DatePickerDialog(this, datepickerListenner, Modulebase.calendar.get(Calendar.YEAR),Modulebase.calendar.get(Calendar.MONTH),Modulebase.calendar.get(Calendar.DAY_OF_MONTH));
	}
	
	DatePickerDialog.OnDateSetListener datepickerListenner = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Modulebase.calendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
			lstFechaVisitas.setAdapter(Modulebase.inicializarFecha());
		}
	};	
	
	private boolean eliminarVisita()
	{
		return Modulebase.db.ejecutarNonQuery("DELETE FROM VISITAS WHERE COD_CLIE='"+idClient+"' AND FECHA='"+itmSelected.getFecha()+"';");
	}

	private void cargarComments()
	{
		//Rellenamos con los comentarios:
				//Sacamos los comentarios:
				lstComments.setAdapter(null);
				Cursor c = Modulebase.db.ejecutarSelect(new String[]{"FECHA ","COMENTARIO","AUSENTE"},"VISITAS", "COD_CLIE=?", new String[]{idClient});
						
				if(c!=null && c.moveToFirst())
				{
					ArrayList<ItmVisita> itmsVisitas = new ArrayList<ItmVisita>();
					do
					{
						boolean ausente = (Integer.parseInt(c.getString(2)) != 0);
						ItmVisita vis = new ItmVisita(c.getString(0), c.getString(1),ausente);
						itmsVisitas.add(vis);
					}while(c.moveToNext());
							
					AdapterVisita adptr = new AdapterVisita(this, itmsVisitas);
					lstComments.setAdapter(adptr);
				}
	}
}